from django.shortcuts import render
from user.models import UserModel,AddressModel
from user.userser import UserSerializer,AddressModelSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from utils.jwttool import tooljwt
from utils.sendmsg import send_message
from utils.myredis import redistoll
from django.db.models import Q
# from .tasks import send
import re
import random
# Create your views here.
class SendCode(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = str(random.randint(1000,9999))
        re_phone = re.match(r"1[3-9]\d{9}",phone)
        if re_phone:
            rediscode = redistoll.getstr(phone)
            if rediscode:
                return Response({"message":"请勿重复发送","code":400})
            else:
                send_message(phone, code)
                redistoll.setstr(phone,code,60*5)
                return Response({"message":"验证码已发送",'code':200})
        else:
            return Response({"message":"请填写正确的手机号","code":400})
class LogView(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = request.data.get('code')
        user = UserModel.objects.get(phone=phone)
        rediscode = redistoll.getstr(phone)
        if rediscode == code:
            data = {
                "id": user.id,
                "token":tooljwt.getToken(user.id,phone)
            }
            return Response({"message":"登录成功","code":200,"data":data})
        else:
            return Response({"message":"验证码不正确","code":400})
class LoginView(APIView):
    def post(self, request):
        account = request.data.get('account')
        password = request.data.get('password')
        user = UserModel.objects.filter(Q(username=account)|Q(email=account)|Q(phone=account)).first()
        if user.password == password:
            data = {
                "id": user.id,
                "account":account,
                "token":tooljwt.getToken(user.id,account)
            }
            return Response({"message":"登录成功","code":200,"data":data})
        else:
            return Response({"message":"账号或密码不正确","code":400})
class Register(APIView):
    def post(self, request):
        serializer = UserSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response({"message":"注册成功","code":200})
        else:
            return Response({"message":serializer.errors,"code":400})
class AddressListAPIView(APIView):
    def get(self, request):
        user_id = request.query_params.get('user_id')
        if not user_id:
            return Response({
                "message": "failed",
                "code": 400,
                "data": {"error": "user_id is required"}
            })
        try:
            user = UserModel.objects.get(id=user_id)
        except UserModel.DoesNotExist:
            return Response({
                "message": "failed",
                "code": 404,
                "data": {"error": "User not found"}
            })

        addresses = AddressModel.objects.filter(user=user)
        serializer = AddressModelSerializer(addresses, many=True)
        return Response({
            "message": "success",
            "code": 200,
            "data": serializer.data
        })

    def post(self, request):
        user_id = request.data.get('user_id')
        if not user_id:
            return Response({
                "message": "failed",
                "code": 400,
                "data": {"error": "user_id is required"}
            })
        try:
            user = UserModel.objects.get(id=user_id)
        except UserModel.DoesNotExist:
            return Response({
                "message": "failed",
                "code": 404,
                "data": {"error": "User not found"}
            })

        data = request.data.copy()
        data['user'] = user.id
        serializer = AddressModelSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                "message": "success",
                "code": 200,
                "data": serializer.data
            })
        return Response({
            "message": "failed",
            "code": 400,
            "data": serializer.errors
        })


class AddressDetailAPIView(APIView):
    def get_object(self, pk, user_id):
        try:
            user = UserModel.objects.get(id=user_id)
            return AddressModel.objects.get(pk=pk, user=user)
        except (AddressModel.DoesNotExist, UserModel.DoesNotExist):
            return None

    def get(self, request, pk):
        user_id = request.query_params.get('user_id')
        if not user_id:
            return Response({
                "message": "failed",
                "code": 400,
                "data": {"error": "user_id is required"}
            })
        address = self.get_object(pk, user_id)
        if address is None:
            return Response({
                "message": "failed",
                "code": 404,
                "data": {"error": "Address not found"}
            })
        serializer = AddressModelSerializer(address)
        return Response({
            "message": "success",
            "code": 200,
            "data": serializer.data
        })

    def put(self, request, pk):
        user_id = request.data.get('user_id')
        if not user_id:
            return Response({
                "message": "failed",
                "code": 400,
                "data": {"error": "user_id is required"}
            })
        address = self.get_object(pk, user_id)
        if address is None:
            return Response({
                "message": "failed",
                "code": 404,
                "data": {"error": "Address not found"}
            })
        data = request.data.copy()
        data['user'] = user_id
        serializer = AddressModelSerializer(address, data=data)
        if serializer.is_valid():
            serializer.save()
            return Response({
                "message": "success",
                "code": 200,
                "data": serializer.data
            })
        return Response({
            "message": "failed",
            "code": 400,
            "data": serializer.errors
        })

    def delete(self, request, pk):
        user_id = request.query_params.get('user_id')
        if not user_id:
            return Response({
                "message": "failed",
                "code": 400,
                "data": {"error": "user_id is required"}
            })
        address = self.get_object(pk, user_id)
        if address is None:
            return Response({
                "message": "failed",
                "code": 404,
                "data": {"error": "Address not found"}
            })
        address.delete()
        return Response({
            "message": "success",
            "code": 200,
            "data": {}
        })

